package com.shop.shopserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shop.shoppojo.entity.Comment;
import com.shop.shoppojo.entity.User;
import com.shop.shoppojo.vo.CommentUserListVO;
import com.shop.shoppojo.vo.CommentUserVO;
import com.shop.shoppojo.vo.CommentVO;

import com.shop.shopserver.mapper.CommentMapper;
import com.shop.shopserver.mapper.UserMapper;
import com.shop.shopserver.service.CommentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class CommentServiceImpl implements CommentService {
    /**
     * 获取商品评论和评论对象的信息
     */

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    public CommentVO getCommentsByGoodsId(String goodsId){
        LambdaQueryWrapper<Comment> commentLambdaQueryWrapper = new LambdaQueryWrapper<Comment>()
                .eq(Comment::getGoodsId,goodsId);
        List<Comment> commentList = commentMapper.selectList(commentLambdaQueryWrapper);
        //用条件构造器查询数据库中有相同的goodsId的商品评论，用commentList接收

        List<CommentUserVO> commentUserVOList=new ArrayList<>();

        commentList.forEach(comment -> {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<User>()
                    .eq(User::getId, comment.getUserId());
            User user = userMapper.selectOne(userLambdaQueryWrapper);

            CommentUserVO commentUserVO = new CommentUserVO();
            // 将Comment对象的属性复制到CommentUserVO
            BeanUtil.copyProperties(comment, commentUserVO);

            if (user != null) {
                // 将User对象的相关属性复制到CommentUserListVO，比如nickName
                CommentUserListVO commentUserListVO = new CommentUserListVO();
                BeanUtil.copyProperties(user, commentUserListVO);
                List<CommentUserListVO> commentUserListVOList=new ArrayList<>();
                commentUserVO.setUser(commentUserListVOList);
                commentUserListVOList.add(commentUserListVO);
            }
            commentUserVOList.add(commentUserVO) ;
        });

        CommentVO commentVO = new CommentVO();
        commentVO.setList(commentUserVOList);
        commentVO.setTotal(commentUserVOList.size());
        return commentVO;

    }

}
